const Goods = require('../db').Goods;

module.exports = {
    //保存商品
    async saveGoods(ctx, next) {
        let { name = '', subName = '', price = '', type = '', img = '', desc = '' } = ctx.request.body;
        if (name == '') {
            ctx.body = {
                code: 401,
                msg: "保存失败，商品名称不能为空!"
            }
            return;
        }
        try {
            let goods = new Goods({
                name,
                subName,
                price,
                type,
                img,
                desc
            });
            let res = await goods.save();
            if (res._id != null) {
                ctx.body = {
                    code: 200,
                    msg: '保存成功！',
                    data: res
                }
            } else {
                ctx.body = {
                    code: 500,
                    msg: '保存失败，服务器异常，请稍后再试!'
                }
            }
        } catch (e) {
            console.log(e);
            ctx.body = {
                code: 500,
                msg: "保存失败，服务器异常，请稍后再试！"
            }
        }
    },
    /* 
      @name: 获取商品
      @param: size => 返回最大个数 默认：10
      @param: page => 当前页数 默认：1
    */
    async getGoods(ctx, next) {
        let { size = 10, page = 1 } = ctx.request.body;
        try {
            let options = {
                skip: Number((page - 1) * size),
                limit: Number(size),
                sort: { "create_time": "-1" }
            }
            let res = await Goods.find({}, null, options);
            let total = await Goods.countDocuments();
            ctx.body = {
                code: 200,
                msg: '获取商品成功',
                data: {
                    list: res,
                    pagination: {
                        total,
                        page: Number(page),
                        size: Number(size)
                    }
                }
            }
        } catch (e) {
            console.log(e);
            ctx.body = {
                code: 500,
                msg: "获取商品失败，服务器异常，请稍后再试！"
            }
        }
    },
}